<?php
/**
 *	[TWCMS] (C)2012 TongWang Inc.
 *	$Id: category_show.php 2 2013-04-27 07:14:17Z nanown@qq.com $
 */
class category_show extends admin{
	public $category;
	public $model;

	function __construct() {
		parent::__construct();
		$this->model = $this->get_model();
		$this->main();
	}

	function main() {
		if(empty($_GET['do'])) {
			$this->category = $this->get_category();
			include load_tpl(__CLASS__);
		}elseif($_GET['do'] == 'ajax_add') {
			$this->ajax_add_edit();
		}elseif($_GET['do'] == 'ajax_get_mid') {
			$this->ajax_get_mid(intget('mid'));
		}elseif($_GET['do'] == 'ajax_get_category_select') {
			$this->get_category_select();
		}elseif($_GET['do'] == 'ajax_get_category_html') {
			 echo $this->get_category_html();
		}elseif($_GET['do'] == 'ajax_get_category_cid') {
			exit(json_encode($this->get_category_cid(intC($_POST, 'cid'))));
		}elseif($_GET['do'] == 'ajax_del') {
			$this->ajax_del();
		}
	}

	#获取分类
	function get_category($upid=0, $pre=-1, $cidExclude=false) {
		$sql = 'SELECT * FROM  `'.TW_DBPRE.'category` WHERE upid='.$upid.' ORDER BY `orderby` ASC';
		$query = $this->db->query($sql);

		++$pre;
		$arr = array();
		while($row=$this->db->fetch_array($query)) {
			if($cidExclude && $row['cid']==$cidExclude) continue;
			$row['pre'] = $pre;
			$arr[] = $row;

			$child = $this->get_category($row['cid'], $pre, $cidExclude);
			if($child) $arr = array_merge($arr, $child);
		}
		return $arr;
	}
	
	#获取分类CID
	function get_category_cid($cid) {
		$data = $this->db->fetch_first('SELECT * FROM  `'.TW_DBPRE.'category` WHERE cid='.$cid);
		if($data['mid'] == 2) {
			$data['pagecontent'] = $this->db->result_first('SELECT content FROM `'.TW_DBPRE.'page` WHERE cid='.S($cid));
		}
		return $data;
	}

	#获取分类SELECT
	function get_category_select($upid=0) {
		echo '<option value="0">顶级目录</option>';
		$categorys = empty($_GET['is_edit']) ? $this->get_category() : $this->get_category(0,-1,intget('cid'));
		$upid = intget('upid');
		foreach($categorys as $lv) {
			echo '<option value="'.$lv['cid'].'"'.($upid == $lv['cid'] ? ' selected="selected"' : '').'>'.str_repeat("　", $lv['pre']).'|─'.$lv['categoryname'].'</option>';
		}
	}

	#获取分类HTML
	function get_category_html($upid=0) {
		$sql = 'SELECT * FROM  `'.TW_DBPRE.'category` WHERE upid='.$upid.' ORDER BY `orderby` ASC';
		$query = $this->db->query($sql);
		$end = $this->db->num_rows($query);

		$i = 0;
		$str = '';
		while($row=$this->db->fetch_array($query)) {
			++$i;
			$sons = $this->get_category_html($row['cid']);
			$son_str = ($sons ? '<div class="pre">'.$sons.'</div>' : '');

			$str .= '<div class="alr'.($i==$end?' end':'').'"><div class="row"><div class="ac" cid="'.$row['cid'].'" title="">'.($son_str ? '<div class="is"></div>' : '').'<div class="info"><input type="checkbox" class="see" /><input class="inp" style="width:40px" type="number" value="'.$row['orderby'].'" />【'.$this->model[$row['mid']].'】'.($row['isindex'] ? '【频道】' : '').(($row['mid']>2 && !$row['isindex']) ? '【内容:'.$row['count'].'】' : '').$row['categoryname'].'('.$row['dir'].')  [cid:'.$row['cid'].'] </div></div></div>'.$son_str.'</div>';
		}
		return $str;
	}

	#AJAX添加/编辑分类
	function ajax_add_edit() {
		$err = 1;
		$name = $msg = '';
		if(empty($_POST)) {
			$msg = '非法访问';
		}else{
			$arr = array();
			$arr['upid'] = intC($_POST, 'upid');
			$arr['mid'] = intC($_POST, 'mid');
			$arr['isindex'] = intC($_POST, 'isindex');
			$arr['categoryname'] = trim($_POST['categoryname']);
			$arr['dir'] = trim($_POST['dir']);
			$arr['seotitle'] = trim($_POST['seotitle']);
			$arr['keywords'] = trim($_POST['keywords']);
			$arr['description'] = trim($_POST['description']);
			$arr['cate_tpl'] = trim($_POST['cate_tpl']);
			$arr['show_tpl'] = trim($_POST['show_tpl']);
			$arr['cate_url'] = trim($_POST['cate_url']);
			$arr['show_url'] = trim($_POST['show_url']);			
			$arr['orderby'] = intC($_POST, 'orderby');			
			$_POST['pagecontent'] = trim($_POST['pagecontent']);

			if(empty($arr['mid'])) {
				$msg = '请选择分类模型';
			}elseif(empty($arr['categoryname'])) {
				$msg = '请填写分类名称';
				$name = 'categoryname';
			}elseif($arr['mid'] == 1) {
				if(empty($arr['dir'])) {
					$msg = '请填写外部URL';
				}else{
					unset($arr['isindex'],$arr['cate_tpl'],$arr['show_tpl'],$arr['cate_url'],$arr['show_url'],$arr['seotitle'],$arr['keywords'],$arr['description']);
				}
			}else{
				$arr['dir'] = urlencode(str_replace(array('/', '\\'), '', $arr['dir']));

				if(empty($arr['dir'])) {
					$msg = '请填写英文目录';
					$name = 'dir';
				}else{
					if($arr['mid'] == 2) {
						unset($arr['isindex'],$arr['show_tpl'],$arr['show_url']);
						if(empty($arr['cate_tpl']) || empty($arr['cate_url'])) {
							$data = $this->db->fetch_first('SELECT cate_tpl,cate_url FROM `'.TW_DBPRE.'model` WHERE mid='.$arr['mid']);
							empty($arr['cate_tpl']) && $arr['cate_tpl'] = $data['cate_tpl'];
							empty($arr['cate_url']) && $arr['cate_url'] = $data['cate_url'];
						}
					}elseif($arr['isindex'] == 1) {
						unset($arr['show_tpl'],$arr['show_url']);
						if(empty($arr['cate_tpl']) || empty($arr['cate_url'])) {
							$data = $this->db->fetch_first('SELECT index_tpl,index_url FROM `'.TW_DBPRE.'model` WHERE mid='.$arr['mid']);
							empty($arr['cate_tpl']) && $arr['cate_tpl'] = $data['index_tpl'];
							empty($arr['cate_url']) && $arr['cate_url'] = $data['index_url'];
						}
					}elseif(empty($arr['cate_tpl']) || empty($arr['cate_url']) || empty($arr['show_tpl']) || empty($arr['show_url'])) {
						$data = $this->db->fetch_first('SELECT cate_tpl,show_tpl,cate_url,show_url FROM `'.TW_DBPRE.'model` WHERE mid='.$arr['mid']);

						empty($arr['cate_tpl']) && $arr['cate_tpl'] = $data['cate_tpl'];
						empty($arr['cate_url']) && $arr['cate_url'] = $data['cate_url'];
						empty($arr['show_tpl']) && $arr['show_tpl'] = $data['show_tpl'];
						empty($arr['show_url']) && $arr['show_url'] = $data['show_url'];
					}

					$arr['parentdir'] = $this->get_parentdir($arr['upid']);
				}
			}

			if(empty($msg)) {
				if($arr['orderby'] == 0) {
					$arr['orderby'] = $this->db->result_first('SELECT orderby FROM `'.TW_DBPRE.'category` WHERE `upid`='.$arr['upid'].' ORDER BY `orderby` DESC LIMIT 1')+1;
				}

				if(empty($_POST['cid'])) {	#添加
					if($this->db->result_first('SELECT count(*) FROM `'.TW_DBPRE.'category` WHERE dir='.S($arr['dir']).' LIMIT 1')) {
						$msg = ($arr['mid'] == 1 ? '外部URL' : '英文目录').'不能重复，请更换';
						$name = 'dir';
					}elseif(!$this->db->insert('category', $arr)) {
						$msg = '操作分类数据表出错';
					}elseif($arr['mid'] == 2 && !$this->set_page($this->db->insert_id())) {
						$msg = '操作单页数据表出错';
					}
				}else{	#编辑
					$cid = intC($_POST, 'cid');
					$data = $this->get_category_cid($cid);
					foreach($arr as $key=>$val) {
						if($val == $data[$key]) unset($arr[$key]);
					}

					if(isset($arr['dir']) && $arr['dir']==$this->db->result_first('SELECT dir FROM `'.TW_DBPRE.'category` WHERE dir='.S($arr['dir']).' LIMIT 1')) {
						$msg = ((empty($arr['mid']) ? $data['mid'] : $arr['mid']) == 1 ? '外部URL' : '英文目录').'不能重复，请更换';
						$name = 'dir';
					}elseif(!empty($arr['upid']) && $arr['upid']==$cid) {
						$name = 'upid';
						$msg = '上级分类不能修改为自己';
					}elseif(!empty($arr['upid']) && $this->checkSubCate($arr['upid'], $cid)) {
						$name = 'upid';
						$msg = '上级分类不能修改为自己下级分类';
					}elseif(!empty($arr['mid']) && $this->checkCount($data)) {
						$name = 'mid';
						$msg = '不允许修改分类模型，因为分类中有内容，如要修改，请先删除内容';
					}elseif(isset($arr['isindex']) && $this->checkCount($data)) {
						$name = 'mid';
						$msg = '不允许修改分类属性，因为分类中有内容，如要修改，请先删除内容';
					}elseif(!empty($arr) && !$this->edit($arr, $cid)) {
						$msg = '操作分类表出错';
					}elseif(isset($data['pagecontent']) && $_POST['pagecontent']!=$data['pagecontent'] && !$this->set_page($cid)) {
						$msg = '操作单页表出错';
					}
				}

				if(empty($msg)) {
					$err = 0;
					$msg = '修改完成';
				}
			}
		}

		exit('{"err":'.$err.', "name":"'.$name.'", "msg":"'.$msg.'"}');
	}

	#编辑分类功能
	function edit($arr, $cid) {
		if(isset($arr['mid']) && $arr['mid']!=2 && !$this->db->query('DELETE FROM `'.TW_DBPRE.'page` WHERE `cid`='.$cid)) return false;
		if(!$this->db->update('category', $arr, 'cid='.$cid)) return false;
		return true;
	}

	#AJAX删除分类
	function ajax_del() {
		$cid = intC($_POST, 'cid');
		$err = 1;
		$data = $this->get_category_cid($cid);

		if($this->checkCount($data)) {
			$msg = '分类中有内容，请先删除内容';
		}elseif($this->db->result_first('SELECT cid FROM `'.TW_DBPRE.'category` WHERE upid='.$cid.' LIMIT 1')) {
			$msg = '分类有下级分类，请先删除下级分类';
		}elseif(!$this->db->query('DELETE FROM `'.TW_DBPRE.'category` WHERE `cid`='.$cid)) {
			$msg = '操作分类表时出错';
		}elseif(!$this->db->query('DELETE FROM `'.TW_DBPRE.'page` WHERE `cid`='.$cid)) {
			$msg = '操作单页表时出错';
		}else{
			$err = 0;
			$msg = '删除完成';
		}
		exit('{"err":'.$err.', "msg":"'.$msg.'"}');
	}

	#写入/修改单页表
	function set_page($cid) {
		if($this->db->result_first('SELECT cid FROM `'.TW_DBPRE.'page` WHERE cid='.S($cid))) {
			return $this->db->query('UPDATE `'.TW_DBPRE.'page` SET `content`='.S($_POST['pagecontent']).' WHERE `cid`='.intval($cid));
		}else{
			return $this->db->query('INSERT INTO `'.TW_DBPRE.'page`(`cid`, `content`) VALUES ('.$cid.', '.S($_POST['pagecontent']).')');
		}
	}

	#AJAX获取模板设置和静态URL规则
	function ajax_get_mid($mid) {
		if($mid == 2) {
			echo tojson($this->db->fetch_first('SELECT cate_tpl,cate_url FROM `'.TW_DBPRE.'model` WHERE mid='.$mid));
		}elseif($mid > 2) {
			if(empty($_GET['isindex'])) {
				echo tojson($this->db->fetch_first('SELECT cate_tpl,show_tpl,cate_url,show_url FROM `'.TW_DBPRE.'model` WHERE mid='.$mid));
			}else{
				echo tojson($this->db->fetch_first('SELECT index_tpl,index_url FROM `'.TW_DBPRE.'model` WHERE mid='.$mid));
			}
		}
		exit;
	}

	#获取模型
	function get_model() {
		$query = $this->db->query('SELECT mid,name FROM `'.TW_DBPRE.'model`');
		$arr = array();
		while($row = $this->db->fetch_array($query)) {
			$arr[$row['mid']] = $row['name'];
		}
		return $arr;
	}

	#获取父级目录
	function get_parentdir($upid) {
		if(empty($upid)) return '';
		
		$dir = '';
		while($row = $this->db->fetch_first('SELECT upid,dir FROM `'.TW_DBPRE.'category` WHERE cid='.$upid)) {
			$upid = $row['upid'];
			$dir = $row['dir'].'/'.$dir;
		}
		return rtrim($dir, '/');
	}

	#检查分类是否存在内容
	function checkCount($data) {
		if($data['mid']>2 && $data['isindex']==0) {
			$count = $this->db->result_first('SELECT count(*) FROM `'.TW_DBPRE.$this->G['modelId'][$data['mid']].'` WHERE cid='.$data['cid']);
			if($count != $data['count']) {
				$this->db->query('UPDATE `'.TW_DBPRE.'category` SET `count`='.$count.' WHERE `cid`='.$data['cid']);
			}
			return $count>0 ? true : false;
		}else{
			if($data['count'] != 0) {
				$this->db->query('UPDATE `'.TW_DBPRE.'category` SET `count`=0 WHERE `cid`='.$data['cid']);
			}
			return false;
		}
	}

	#检查是否是自己的下级分类
	function checkSubCate($upid, $cid) {
		return in_array($upid, $this->getSonCate($cid));
	}

	#递归获取所有子分类CID
	function getSonCate($cid) {
		$query = $this->db->query('SELECT cid FROM `'.TW_DBPRE.'category` WHERE upid='.$cid);
		$arr = array();
		while($row = $this->db->fetch_array($query)) {
			$arr[] = $row['cid'];
			$child = $this->getSonCate($row['cid']);
			if($child) $arr = array_merge($arr, $child);
		}
		return $arr;
	}
}